import { createStore, applyMiddleware } from 'redux'
import { thunk } from 'redux-thunk'
import axios from 'axios';

let init = {
  val: "",  // 存储 todo input框里输入值的state
  list: []
}

function reducer(state = init, action) {
  if (action.type === "changeText") {
    return { ...state, val: action.payload }
  }

  if (action.type === "updateList") {
    return { ...state, list: action.payload };
  }
  return state;
}

let store = createStore(reducer, applyMiddleware(thunk));

export function changeTextAction(payload) {
  return { type: "changeText", payload }
}

// 异步的action 提交 todo的数据
export function asyncSubTodoAction(payload) {
  return async function (dispatch) {
    // axios.post("/api/addList",payload).then(res=>{
    //     console.log(res);
    // })
    let res = await axios.post("/api/addList", payload)
    return res;
  }
}


// 异步action获取dotolist里的数据
export function asyncGetListAction() {
  return async function (dispatch) {
    let { data } = await axios.get("/api/getlist");
    // 把获取到的data列表数据 dispatch到state里面
    // console.log(data);
    dispatch({ type: "updateList", payload: data })
    console.log("state:", store.getState());
  }
}



// 修改 勾选的状态 
export function asyncChangeCheckAction(id) {
  return async function (dispatch) {
    let res = await axios.put("/api/ChangeCheck", { id })
    // console.log(res);
    return res;
  }
}


// 删除todolist 
export function asyncDelTodoAction(id) {
  return async function () {

    /* 
        第一类 ： 2个参数   ： 
            axios.get  axios.delete  axios.head(url,配置项)
        第二类 ： 3个参数
            axios.post   axios.put   axios.pathch(url,data,配置项)
    */
    let res = await axios.delete("/api/deltodo", { params: { id } });
    // console.log(res);
    return res;
  }
}



export default store;
